package utils

import (
	"math/rand"
	"net/url"
	"reflect"
	"strconv"
	"time"
)

// StructToQueryString 将结构体转换为 URL 编码的查询字符串
func StructToQueryString(v interface{}) string {
	val := reflect.ValueOf(v).Elem()
	typeOfS := val.Type()

	params := url.Values{}
	for i := 0; i < val.NumField(); i++ {
		field := val.Field(i)
		key := typeOfS.Field(i).Tag.Get("form")

		switch field.Kind() {
		case reflect.String:
			params.Add(key, field.String())
		case reflect.Int:
			params.Add(key, strconv.Itoa(int(field.Int())))
		case reflect.Int64:
			params.Add(key, strconv.FormatInt(field.Int(), 10))
		case reflect.Float64:
			params.Add(key, strconv.FormatFloat(field.Float(), 'f', -1, 64))
		}
	}

	return params.Encode()
}

// GenerateRandomString 随机生成字符串的函数
func GenerateRandomString(length int) string {
	const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
	var seededRand *rand.Rand = rand.New(
		rand.NewSource(time.Now().UnixNano()))

	randomString := make([]byte, length)
	for i := range randomString {
		randomString[i] = charset[seededRand.Intn(len(charset))]
	}
	return string(randomString)
}
